package org.liaohailong.library.http.download;

import androidx.annotation.NonNull;

import org.liaohailong.library.http.HttpHelper;
import org.liaohailong.library.http.IHttpCallback;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * Author: liaohailong
 * Date: 2022/8/28
 * Time: 23:10
 * Description:
 **/
public class ProgressResponseBody extends ResponseBody {
    @NonNull
    private final ResponseBody body;
    @NonNull
    private final IHttpCallback<?> callback;

    private BufferedSource bufferedSource;

    public ProgressResponseBody(@NonNull ResponseBody body, @NonNull IHttpCallback<?> callback) {
        this.body = body;
        this.callback = callback;
    }

    @Override
    public MediaType contentType() {
        return body.contentType();
    }

    @Override
    public long contentLength() {
        return body.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(new ProgressBufferSource(body.source()));
        }
        return bufferedSource;
    }


    private final class ProgressBufferSource extends ForwardingSource {

        private long totalLength = -1;
        private long currentLength = 0;

        public ProgressBufferSource(Source delegate) {
            super(delegate);
        }

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            if (totalLength == -1) {
                totalLength = body.contentLength();
            }

            long readLength = super.read(sink, byteCount);
            currentLength += readLength > 0 ? readLength : 0;

            HttpHelper.post2main(() -> {
                callback.onProgress(currentLength, totalLength);
            });
            return readLength;
        }
    }

}
